package ${package}.domain.eventbus.config;

import com.google.common.eventbus.AsyncEventBus;
import ${package}.domain.eventbus.events.SimpleEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Service;

/**
 * @Desc   注册事件类
 * @Author GuoFeng
 * @Date 2019/3/5
 */
@Slf4j
@Service
public class EventBusAdapter implements ApplicationContextAware, SmartLifecycle {

    private ApplicationContext applicationContext;

    @Autowired
    private AsyncEventBus asyncEventBus;

    private boolean flag = false;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void start() {
        this.applicationContext.getBeansWithAnnotation(EventBusRegister.class).forEach((name, bean) -> {
            this.asyncEventBus.register(bean);
            log.info("已注册EventBus事件类:{}", name);
        });
        flag = true;
        //发送测试消息
        asyncEventBus.post(new SimpleEvent("测试消息"));
    }

    @Override
    public void stop() {
        flag = false;
    }

    @Override
    public boolean isRunning() {
        return flag;
    }
}
